package com.fighter.controller;

import com.fighter.mapper.FightOrderMapper;
import com.fighter.utils.OverTimeJudge;
import com.order.hit.crossover.platform.common.bean.Friend;
import com.order.hit.crossover.platform.common.bean.Notice;
import com.order.hit.crossover.platform.common.bean.order.FightOrderState;
import com.order.hit.crossover.platform.common.bean.order.Fightorder;
import com.order.hit.crossover.platform.common.dao.FightOrderDao;
import com.order.hit.crossover.platform.common.utils.PFResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Lei
 * @version 0.1
 * @date 2020/9/8
 */
@RestController
@RequestMapping("/fightorder")
public class FightOrderController {

    @Autowired
    private FightOrderMapper fightOrderMapper;

    @Autowired
    private OverTimeJudge overTimeJudge;

    // 添加订单
    @PostMapping("/addFightOrder")
    public PFResponse addFightOrder(@RequestBody FightOrderDao fightOrderDao){
        PFResponse pfResponse = new PFResponse();
        try{
            this.fightOrderMapper.insertFightOrder(fightOrderDao);
            pfResponse.code(200);
            pfResponse.message("添加成功");
        }catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("添加失败");
        }
        overTimeJudge.judgeFightOrderIfOverTime();
        return pfResponse;
    }

    // 删除订单
    @DeleteMapping("/deleteFightOrder/{id}")
    public PFResponse deleteFightOrder(@PathVariable("id") int id){
        PFResponse pfResponse = new PFResponse();
        try{
            this.fightOrderMapper.deleteOrder(id);
            pfResponse.code(200);
            pfResponse.message("删除成功");
        }catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("删除失败");
        }
        overTimeJudge.judgeFightOrderIfOverTime();
        return pfResponse;
    }

    // 得到商店的拼单
    @GetMapping("/getStoreOrder/{id}")
    public PFResponse getStoreOerder(@PathVariable("id")String id){
        overTimeJudge.judgeFightOrderIfOverTime();
        PFResponse pfResponse = new PFResponse();
        List<FightOrderDao> list = this.fightOrderMapper.getStoresOrder(id);
        List<Fightorder> result = new ArrayList<>();
        for (FightOrderDao fightOrderDao : list){
            result.add(FightOrderDao.getOrder(fightOrderDao));
        }
        pfResponse.code(200);
        pfResponse.message("查询成功");
        pfResponse.data(result);
        return pfResponse;
    }

    // 得到某个人所有可见的拼单
    @GetMapping("/getUserSeeOrder/{id}")
    public PFResponse getSeeOrder(@PathVariable("id")int id){
        overTimeJudge.judgeFightOrderIfOverTime();
        PFResponse pfResponse = new PFResponse();
        try {
            List<Fightorder> result = new ArrayList<>();
            List<Friend> friends = (List<Friend>)new RestTemplate().exchange("http://friend:18082/friend/getRequestFriend/" + id, HttpMethod.GET, new HttpEntity<>(new HttpHeaders()), PFResponse.class).getBody().get("data");
            for (Friend friend: friends){
                List<FightOrderDao> list = this.fightOrderMapper.getUsersOrder(friend.getFriendId());
                for (FightOrderDao fightOrderDao:list){
                    if (fightOrderDao.getFightOrderState().equals(FightOrderState.ORDER_DISPLAY.toString())){
                        result.add(FightOrderDao.getOrder(fightOrderDao));
                    }
                }
            }
            pfResponse.code(200);
            pfResponse.message("查询成功");
            pfResponse.data(result);
        }catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("查询失败");
        }

        return pfResponse;
    }

    // 得到某个人的所有发起拼单
    @GetMapping("/getUserOrder/{id}")
    public PFResponse getUserOerder(@PathVariable("id")int id){
        overTimeJudge.judgeFightOrderIfOverTime();
        PFResponse pfResponse = new PFResponse();
        List<FightOrderDao> list = this.fightOrderMapper.getUsersOrder(id);
        List<Fightorder> result = new ArrayList<>();
        for (FightOrderDao fightOrderDao : list){
            result.add(FightOrderDao.getOrder(fightOrderDao));
        }
        pfResponse.code(200);
        pfResponse.message("查询成功");
        pfResponse.data(result);
        return pfResponse;
    }

    //得到某人参与的拼单，发起的除外
    @GetMapping("/getPaOrder/{id}")
    public PFResponse getPaOrder(@PathVariable("id")int id){
        PFResponse pfResponse = new PFResponse();
        try{
            List<Fightorder> result = new ArrayList<>();
            List<FightOrderDao> list = this.fightOrderMapper.getAllFightOrder();
            for (FightOrderDao fightOrderDao: list){
                String[] pal = fightOrderDao.getParticipaters().split("\\.");
                for(int i =0;i<pal.length;i++){
                    if (i!=0 && String.valueOf(id).equals(pal[i])) {
                        result.add(FightOrderDao.getOrder(fightOrderDao));
                        break;
                    }
                }
            }
            pfResponse.code(200);
            pfResponse.message("查询成功");
            pfResponse.data(result);
        } catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("查询失败");
            pfResponse.data(null);
        }
        return pfResponse;
    }


    // 修改订单状态
    @PutMapping("/changeState")
    public PFResponse changeState(@RequestParam("state")String state, @RequestParam("id") Long id){
        PFResponse pfResponse = new PFResponse();
        try{
            FightOrderDao fightOrderDao = this.fightOrderMapper.getOrderById(id);
            fightOrderDao.setFightOrderState(state.toUpperCase());
            pfResponse.code(200);
            pfResponse.message("修改成功");

            String goodname = fightOrderDao.getGoodName();
            //  为订单发起顾客生成通知
            Notice from_notice = new Notice("您发起的关于" + goodname + "的拼单已成交，请前往我发起的拼单界面查看详细信息",0,1,fightOrderDao.getUserId()+"");
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(from_notice, new HttpHeaders()), PFResponse.class);

            //  为参与拼单的顾客生成通知
            String[] pal = fightOrderDao.getParticipaters().split("\\.");
            for(String cs_id:pal) {
                Notice to_notice = new Notice("您参与的关于" + goodname + "的拼单已成交，请前往我参与的拼单界面查看详细信息",0,1,cs_id);
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(to_notice, new HttpHeaders()), PFResponse.class);

            }
            //  为门店生成通知
            Notice store_notice = new Notice("您出售的关于商品" + goodname + "的拼单已成交，请前往我的拼单界面查看详细信息",0,0,fightOrderDao.getStoreId());
            new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(store_notice, new HttpHeaders()), PFResponse.class);

        }catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("修改失败");
        }
        return pfResponse;
    }

    // 参与拼单
    @PutMapping("/join")
    public PFResponse pindan(@RequestParam("id")Long id, @RequestParam("userId")int userId){
        PFResponse pfResponse = new PFResponse();
        try{
            FightOrderDao fightOrderDao = this.fightOrderMapper.getOrderById(id);
            int nowNum = fightOrderDao.getNowNum();
            int num = fightOrderDao.getUserNum();

            String[] pal = fightOrderDao.getParticipaters().split("\\.");

            for(String s: pal) {
                if((userId+"").equals(s)) {
                    pfResponse.code(201);
                    pfResponse.message("您已参与此拼单！");
                    return pfResponse;
                }
            }

            nowNum = nowNum + 1;
            fightOrderDao.setNowNum(nowNum);
            if (nowNum == num){
                fightOrderDao.setFightOrderState(FightOrderState.ORDER_SUCCESS.toString());
                //  生成通知
                String goodname = fightOrderDao.getGoodName();
                //  为订单发起顾客生成通知
                Notice from_notice = new Notice("您发起的关于" + goodname + "的拼单已成功",0,1,fightOrderDao.getUserId()+"");
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(from_notice, new HttpHeaders()), PFResponse.class);

                //  为参与拼单的顾客生成通知
                String[] pal_list = fightOrderDao.getParticipaters().split("\\.");
                for(String cs_id:pal_list) {
                    if(cs_id.equals(fightOrderDao.getUserId()+"")) {
                        continue;
                    }
                    Notice to_notice = new Notice("您参与的关于" + goodname + "的拼单已成功",0,1,cs_id);
                    new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(to_notice, new HttpHeaders()), PFResponse.class);

                }
                //  为当前参与拼单用户生成通知
                Notice now_notice = new Notice("您参与的关于商品" + goodname + "的拼单已成功",0,1,userId+"");
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(now_notice, new HttpHeaders()), PFResponse.class);

                //  为门店生成通知
                Notice store_notice = new Notice("您出售的关于商品" + goodname + "的拼单已成功",0,0,fightOrderDao.getStoreId());
                new RestTemplate().exchange("http://notice:18083/Notice/add", HttpMethod.POST, new HttpEntity<>(store_notice, new HttpHeaders()), PFResponse.class);

            }
            StringBuilder stringBuilder = new StringBuilder(fightOrderDao.getParticipaters());
            stringBuilder.append("." + userId);
            fightOrderDao.setParticipaters(stringBuilder.toString());
            this.fightOrderMapper.updateOrder(fightOrderDao);
            pfResponse.code(200);
            pfResponse.message("拼单成功");
        }
        catch (Exception e){
            pfResponse.code(500);
            pfResponse.message("拼单失败");
        }
        return pfResponse;
    }
}
